package com.cloud.wms.ui.in.inventory;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.cloud.core.utils.DateUtil;
import com.cloud.core.utils.NumberUtils;
import com.cloud.core.utils.TimeUtils;
import com.cloud.widget.ScanText;
import com.cloud.wms.R;
import com.cloud.wms.app.FineExApplication;
import com.cloud.wms.base.BaseBarActivity;
import com.cloud.wms.config.IntentKey;
import com.cloud.wms.tools.DatePickerUtils;
import com.cloud.wms.ui.in.contract.InInventoryContract;
import com.cloud.wms.ui.in.entity.InCommodityEntity;
import com.cloud.wms.ui.in.presnter.InInventoryPresenter;
import com.cloud.wms.ui.main.entity.MemberEntity;
import com.cloud.wms.ui.main.entity.TaskEntity;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @Author:Chen
 * @Date: 2021-01-23 10:18
 * @Description: 无单--批量清点
 */
public class NoBatchActivity extends BaseBarActivity<InInventoryPresenter> implements InInventoryContract.View {
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    @BindView(R.id.scan_text)
    ScanText scanText;
    @BindView(R.id.btn_good)
    CheckedTextView btnGood;
    @BindView(R.id.btn_bad)
    CheckedTextView btnBad;
    @BindView(R.id.tv_member_name)
    TextView tvMemberName;
    @BindView(R.id.iv_member_name)
    ImageView ivMemberName;
    @BindView(R.id.tv_commodity_code)
    TextView tvCommodityCode;
    @BindView(R.id.tv_commodity_name)
    TextView tvCommodityName;
    @BindView(R.id.tv_produce_date)
    TextView tvProduceDate;
    @BindView(R.id.tv_deadline_date)
    TextView tvDeadlineDate;
    @BindView(R.id.tv_in_date)
    TextView tvInDate;
    @BindView(R.id.et_commodity_amount)
    EditText etCommodityAmount;
    @BindView(R.id.btn_next)
    TextView btnNext;
    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            verifyRequired();
        }
    };
    private InCommodityEntity commodityEntity;
    private ArrayList<InCommodityEntity> inCommodityList = new ArrayList<>();
    private DatePickerDialog mDateDialog;
    private String beginTime;

    @Override
    protected String barTitle() {
        return "批量清点";
    }

    @Override
    protected int getResId() {
        return R.layout.activity_in_inventory_no_batch;
    }

    @Override
    protected void setupComponent() {
        getActivityComponent().inject(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MemberEntity memberInfo = FineExApplication.component().loginCache().getMemberInfo();
        if (tvMemberName != null && memberInfo != null) {
            tvMemberName.setText(memberInfo.getMemberName());
        }
    }

    @Override
    protected void initEvent() {
        beginTime = TimeUtils.getCurrentDateAndTime();
        btnSubmit.setEnabled(false);
        btnNext.setEnabled(false);
        btnGood.setChecked(true);
        initScanText(scanText);
        tvInDate.setText(DateUtil.format_yyyy_MM_dd(System.currentTimeMillis()));
        etCommodityAmount.addTextChangedListener(textWatcher);
    }

    @Override
    protected void onScanHandle(String result, int resultCode) {
        super.onScanHandle(result, resultCode);
        scanText.addHistory(result);
        mPresenter.checkCommodityCode(null, result);
    }

    private void verifyRequired() {
        if (commodityEntity == null) {
            btnSubmit.setEnabled(false);
            btnNext.setEnabled(false);
            return;
        }
        String produceDate = tvProduceDate.getText().toString().trim();
        if (TextUtils.isEmpty(produceDate)) {
            btnSubmit.setEnabled(false);
            btnNext.setEnabled(false);
            return;
        }
        String deadlineDate = tvDeadlineDate.getText().toString().trim();
        if (TextUtils.isEmpty(deadlineDate)) {
            btnSubmit.setEnabled(false);
            btnNext.setEnabled(false);
            return;
        }
        String inDate = tvInDate.getText().toString().trim();
        if (TextUtils.isEmpty(inDate)) {
            btnSubmit.setEnabled(false);
            btnNext.setEnabled(false);
            return;
        }
        String commodityAmount = etCommodityAmount.getText().toString().trim();
        if (TextUtils.isEmpty(commodityAmount)) {
            btnSubmit.setEnabled(false);
            btnNext.setEnabled(false);
            return;
        }
        btnSubmit.setEnabled(true);
        btnNext.setEnabled(true);
    }

    private void dateSelector(TextView textView, boolean isTodayAfter) {
        mDateDialog = DatePickerUtils.datePicker(this,
                isTodayAfter,
                (view, year, month, dayOfMonth) -> {
                    String date = DateUtil.formatYMD(year, month + 1, dayOfMonth);
                    textView.setText(date);
                    verifyRequired();
                });
        mDateDialog.show();
    }

    private boolean verifySubmit() {
        if (commodityEntity == null) {
            info("请先扫描商品");
            return false;
        }
        String produceDate = tvProduceDate.getText().toString().trim();
        if (TextUtils.isEmpty(produceDate)) {
            info("生产日期为必填项");
            return false;
        }
        String deadlineDate = tvDeadlineDate.getText().toString().trim();
        if (TextUtils.isEmpty(deadlineDate)) {
            info("截止日期为必填项");
            return false;
        }
        String inDate = tvInDate.getText().toString().trim();
        if (TextUtils.isEmpty(inDate)) {
            info("入库时间为必填项");
            return false;
        }
        String commodityAmount = etCommodityAmount.getText().toString().trim();
        if (TextUtils.isEmpty(commodityAmount)) {
            info("清点数量为必填项");
            return false;
        }
        if (!NumberUtils.isInt(commodityAmount) || NumberUtils.getIntegerValue(commodityAmount) <= 0) {
            info("清点数量必须为整数且必须大于0");
            return false;
        }

        int commodityType = 1;
        if (btnBad.isChecked()) commodityType = 2;

        commodityEntity.setProductionDate(produceDate);
        commodityEntity.setExpirationDate(deadlineDate);
        commodityEntity.setInDate(inDate);
        commodityEntity.setAmount(NumberUtils.getIntegerValue(commodityAmount));
        commodityEntity.setStockType(commodityType);
        return true;
    }

    @Override
    public void onSuccess(Message message) {
        switch (message.what) {
            case InInventoryPresenter.IN_CHECK_CODE:
                commodityEntity = (InCommodityEntity) message.obj;
                tvCommodityName.setText(commodityEntity.getCommodityName());
                tvCommodityCode.setText(commodityEntity.getBarCode());
                commodityEntity.setStockType(btnBad.isChecked() ? 2 : 1);
                break;
            case InInventoryPresenter.IN_BATCH_VERIFY:
                inCommodityList.add(commodityEntity);
                success("请继续下一个!");
                resetView();
                break;
            case InInventoryPresenter.IN_BATCH_SUBMIT:
                success("清点提交成功!");
                resetView();
                break;
        }
    }

    private void resetView() {
        inCommodityList.clear();
        commodityEntity = null;
        btnSubmit.setEnabled(false);
        btnNext.setEnabled(false);
        btnGood.setChecked(true);
        btnBad.setChecked(false);
        tvInDate.setText(DateUtil.format_yyyy_MM_dd(System.currentTimeMillis()));
        tvCommodityCode.setText("");
        tvCommodityName.setText("");
        tvDeadlineDate.setText("");
        tvProduceDate.setText("");
        etCommodityAmount.setText("");
    }

    @OnClick({R.id.btn_good, R.id.btn_bad, R.id.tv_member_name, R.id.iv_member_name, R.id.tv_produce_date, R.id.iv_produce_date, R.id.tv_deadline_date, R.id.iv_deadline_date, R.id.tv_in_date, R.id.iv_in_date, R.id.btn_submit, R.id.btn_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_good:
                btnGood.setChecked(true);
                btnBad.setChecked(false);
                switchCommodityType();
                break;
            case R.id.btn_bad:
                btnGood.setChecked(false);
                btnBad.setChecked(true);
                switchCommodityType();
                break;
            case R.id.tv_member_name:
            case R.id.iv_member_name:
                switchMember();
                break;
            case R.id.tv_produce_date:
            case R.id.iv_produce_date:
                dateSelector(tvProduceDate, false);
                break;
            case R.id.tv_deadline_date:
            case R.id.iv_deadline_date:
                dateSelector(tvDeadlineDate, true);
                break;
            case R.id.tv_in_date:
            case R.id.iv_in_date:
                dateSelector(tvInDate, true);
                break;
            case R.id.btn_submit:
                if (verifySubmit()) {
                    inCommodityList.add(commodityEntity);
                    mPresenter.submitSingleNoOrderInventory(
                            inCommodityList, beginTime);
                }
                break;
            case R.id.btn_next:
                if (verifySubmit()) {
                    mPresenter.verifySubmit(
                            null,
                            commodityEntity);
                }
                break;
        }
    }

    private void switchCommodityType() {
        if (commodityEntity != null) {
            int commodityType = 1;
            if (btnBad.isChecked()) commodityType = 2;
            commodityEntity.setStockType(commodityType);
        }
    }

    public static void start(Context context) {
        Intent intent = new Intent(context, NoBatchActivity.class);
        context.startActivity(intent);
    }
}
